package com.hfy.admin.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static constants.RedisConstants.ADMIN_LOGIN_TOKEN_KEY;

/**
 * @ author 韩
 * time: 2024/5/13 22:32
 */
@Component
public class Interceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = ADMIN_LOGIN_TOKEN_KEY + request.getHeader("token");

        try {
            String idFromToken = (String) redisTemplate.opsForHash().get(token, "id");
            String emailFromToken = (String) redisTemplate.opsForHash().get(token, "email");
            if (idFromToken == null) {
                response.setStatus(401); // 未授权
                return false;
            }
            if (!idFromToken.equals(request.getSession().getAttribute("id")) &&
                    request.getSession().getAttribute("id") != null) {

                response.setStatus(401); // 未授权
                return false;
            }


            // 第一次一定会执行
            request.getSession().setAttribute("id", idFromToken);
            request.getSession().setAttribute("email", emailFromToken);

            // 放行
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }
}
